﻿using DataAcquisition.CustomControls;
using gl_SMT.Model;
using Microsoft.Office.Interop.Excel;
using Microsoft.Win32;
using SMTUploadProductionData.model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Application = Microsoft.Office.Interop.Excel.Application;

namespace gl_SMT.View
{
    /// <summary>
    /// UserControlDataSelect.xaml 的交互逻辑
    /// </summary>
    public partial class gkg_DataSelect : UserControl
    {
        public gkg_DataSelect()
        {
            InitializeComponent();
            this.Loaded += gkg_ControlDataSelect_Loaded;
        }

        public string MachineName { get; set; }
        DatabaseReadWrite database = new DatabaseReadWrite();
        private void gkg_ControlDataSelect_Loaded(object sender, RoutedEventArgs e)
        {
            InitializeTime();
            dp_SatrtDate.Text = DateTime.Now.ToString();
            dp_EndDate.Text = DateTime.Now.ToString();
            SelectData();
        }

        private void InitializeTime()
        {
            for (int i = 0; i < 24; i++)
            {
                cb_sHour.Items.Add(i.ToString("D2"));
                cb_eHour.Items.Add(i.ToString("D2"));
            }
            cb_sHour.SelectedIndex = 0;
            cb_eHour.SelectedIndex = 23;

            for (int i = 0; i < 60; i++)
            {
                cb_sMinute.Items.Add(i.ToString("D2"));
                cb_sSecond.Items.Add(i.ToString("D2"));
                cb_eMinute.Items.Add(i.ToString("D2"));
                cb_eSecond.Items.Add(i.ToString("D2"));
            }
            cb_sMinute.SelectedIndex = 0;
            cb_sSecond.SelectedIndex = 0;
            cb_eMinute.SelectedIndex = 59;
            cb_eSecond.SelectedIndex = 59;
        }

        private void btn_Select_Click(object sender, RoutedEventArgs e)
        {
            SelectData();
        }

        private void SelectData()
        {
            string sta_DateTime = $"{dp_SatrtDate.Text} {cb_sHour.Text}:{cb_sMinute.Text}:{cb_sSecond.Text}";//开始日期和时间
            string end_DateTime = $"{dp_EndDate.Text} {cb_eHour.Text}:{cb_eMinute.Text}:{cb_eSecond.Text}";//结束日期和时间
            List<gkg_model> gkg_Models = database.QueryData<gkg_model>("gkg_Producedate", "MachineName", MachineName.Split(' ')[1], sta_DateTime, end_DateTime, "TimeStamp", "DATETIME");
            dataGrid.ItemsSource = gkg_Models;//将数据绑定datagrid
            txt_SelectNumber.Text = gkg_Models.Count.ToString();//获取查询的数据量
            txt_PcbNumber.Text = CountPcbNumber(gkg_Models).ToString();//获取pcb的数量
            txt_Speed.Text = PrintingSpeed(gkg_Models).ToString();//获取机台运行速度
            txt_CycleTime.Text= PrintingCycleTime(gkg_Models).ToString();//获取机台生产周期
            txt_Aml.Text = gkg_EquipmentAlm(MachineName.Split(' ')[1]);//获取报警数量
        }


        private void btn_Export_Click(object sender, RoutedEventArgs e)
        {
            
            string sta_DateTime = $"{dp_SatrtDate.Text} {cb_sHour.Text}:{cb_sMinute.Text}:{cb_sSecond.Text}";
            string end_DateTime = $"{dp_EndDate.Text} {cb_eHour.Text}:{cb_eMinute.Text}:{cb_eSecond.Text}";
            List<gkg_model> gkg_Models = database.QueryData<gkg_model>("gkg_Producedate", "MachineName", MachineName.Split(' ')[1], sta_DateTime, end_DateTime, "TimeStamp", "DATETIME");
            DataExport(gkg_Models);//导出数据
        }

        /// <summary>
        /// 数据导出
        /// </summary>
        private void DataExport(List<gkg_model> gkg_Models)
        {
            SaveFileDialog saveFile = new SaveFileDialog();
            saveFile.Filter = "Excel Worksheets|*.xls";
            if (saveFile.ShowDialog() == true)
            {
                Application excelApp = new Application();
                Workbook workbook = excelApp.Workbooks.Add();
                Worksheet worksheet = (Worksheet)workbook.ActiveSheet;

                for (int i = 0; i < dataGrid.Columns.Count; i++)
                {
                    worksheet.Cells[1, i + 1] = dataGrid.Columns[i].Header.ToString();// 设置表头
                }

                for (int i = 0; i < gkg_Models.Count; i++)
                {
                    worksheet.Cells[2 + i, 1] = gkg_Models[i].MachineName;
                    worksheet.Cells[2 + i, 2] = gkg_Models[i].BarCode;
                    worksheet.Cells[2 + i, 3] = gkg_Models[i].TimeStamp;
                    worksheet.Cells[2 + i, 4] = gkg_Models[i].FileName;
                    worksheet.Cells[2 + i, 5] = gkg_Models[i].ProgramRunning;
                    worksheet.Cells[2 + i, 6] = gkg_Models[i].PCBNumber;
                    worksheet.Cells[2 + i, 7] = gkg_Models[i].ProdName;
                    worksheet.Cells[2 + i, 8] = gkg_Models[i].ProdType;
                    worksheet.Cells[2 + i, 9] = gkg_Models[i].CycleTime;
                    worksheet.Cells[2 + i, 10] = gkg_Models[i].SPIResult;
                    worksheet.Cells[2 + i, 11] = gkg_Models[i].PrintSpeed;
                    worksheet.Cells[2 + i, 12] = gkg_Models[i].FrontSQGPress;
                    worksheet.Cells[2 + i, 13] = gkg_Models[i].RearSQGPress;
                    worksheet.Cells[2 + i, 14] = gkg_Models[i].PrintMode;
                    worksheet.Cells[2 + i, 15] = gkg_Models[i].PrintGap;
                    worksheet.Cells[2 + i, 16] = gkg_Models[i].SnapOffDistance;
                    worksheet.Cells[2 + i, 17] = gkg_Models[i].SnapOffSpeed;
                    worksheet.Cells[2 + i, 18] = gkg_Models[i].SnapOffDelay;
                    worksheet.Cells[2 + i, 19] = gkg_Models[i].SQGUpSpeed;
                    worksheet.Cells[2 + i, 20] = gkg_Models[i].SQGDownSpeed;
                    worksheet.Cells[2 + i, 21] = gkg_Models[i].SQGUpFirst;
                    worksheet.Cells[2 + i, 22] = gkg_Models[i].SQGHeightAtSnapOff;
                    worksheet.Cells[2 + i, 23] = gkg_Models[i].CleaningAfterLastBoard;
                    worksheet.Cells[2 + i, 24] = gkg_Models[i].CleaningFrequency;
                    worksheet.Cells[2 + i, 25] = gkg_Models[i].CleaningSpeed;
                    worksheet.Cells[2 + i, 26] = gkg_Models[i].CleaningMode;
                    worksheet.Cells[2 + i, 27] = gkg_Models[i].CleaningType;
                    worksheet.Cells[2 + i, 28] = gkg_Models[i].AddSPMode;
                    worksheet.Cells[2 + i, 29] = gkg_Models[i].AddSPAfterLastBoard;
                    worksheet.Cells[2 + i, 30] = gkg_Models[i].DSPIResult;
                    worksheet.Cells[2 + i, 31] = gkg_Models[i].PrintDirection;
                    worksheet.Cells[2 + i, 32] = gkg_Models[i].PCBSize;
                }
                worksheet.Columns.AutoFit();// 自动调整列宽
                workbook.SaveAs(saveFile.FileName);// 保存文件
                workbook.Close();//关闭文档
                excelApp.Quit();//退出

                // 释放 COM 对象
                System.Runtime.InteropServices.Marshal.ReleaseComObject(worksheet);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
                MessageBox.Show("导出完成");
            }
        }

        /// <summary>
        /// 计算pcb数量
        /// </summary>
        /// <param name="gkg_Models"></param>
        /// <returns></returns>
        private int CountPcbNumber(List<gkg_model> gkg_Models)
        {
            List<int> list_Number = new List<int>();
            DateTime Statime = DateTime.Parse(dp_SatrtDate.Text);
            DateTime Endtime = DateTime.Parse(dp_EndDate.Text);
            TimeSpan span = Endtime - Statime;
            int day = span.Days + 1;
            for (int i = 0; i < day; i++)
            {
                List<int> list = new List<int>();
                for (int j = 0; j < gkg_Models.Count; j++)
                {
                    if (Statime.AddDays(i).ToString("yyyy-MM-dd") == DateTime.Parse(gkg_Models[j].TimeStamp).ToString("yyyy-MM-dd"))
                    {
                        list.Add(gkg_Models[j].PCBNumber);
                    }
                }
                if (list.Count == 0) continue;
                list_Number.Add(list[list.Count-1]- list[0]);
            }
            return list_Number.Sum();
        }

        private int PrintingCycleTime(List<gkg_model> gkg_Models)
        {
            if (gkg_Models.Count()==0) return 0;
            return (int)gkg_Models.Average(t => int.Parse(t.CycleTime));
        }

        /// <summary>
        /// 平均速度
        /// </summary>
        /// <param name="gkg_Models"></param>
        /// <returns></returns>
        private int PrintingSpeed(List<gkg_model> gkg_Models)
        {
            double Speed = 0;
            if (gkg_Models.Count == 0) return 0;
            Speed = gkg_Models.Average(t => double.Parse(t.PrintSpeed));
            if (Speed == 0) return 0;
            return (int)Speed;
        }

        private string gkg_EquipmentAlm(string name)
        {
            string sta_DateTime = $"{dp_SatrtDate.Text} {cb_sHour.Text}:{cb_sMinute.Text}:{cb_sSecond.Text}";
            string end_DateTime = $"{dp_EndDate.Text} {cb_eHour.Text}:{cb_eMinute.Text}:{cb_eSecond.Text}";
            string selectAlm = $"select * from gkg_Event where MachineName ='{name}' " +
                $"AND CAST(Event_Day AS DATETIME) + CAST(Event_Time AS DATETIME) >= '{sta_DateTime}' " +
                $"AND CAST(Event_Day AS DATETIME) + CAST(Event_Time AS DATETIME) <= '{end_DateTime}'";
            System.Data.DataTable dt = database.SelectData(selectAlm);
            return dt.Rows.Count.ToString();
        }

        private void btn_OPEvent_Click(object sender, RoutedEventArgs e)
        {
            OPEventWindow oPEvent= new OPEventWindow();
            oPEvent.Name = MachineName.Split(' ')[1];
            oPEvent.sta_DateTime = $"{dp_SatrtDate.Text} {cb_sHour.Text}:{cb_sMinute.Text}:{cb_sSecond.Text}";
            oPEvent.end_DateTime = $"{dp_EndDate.Text} {cb_eHour.Text}:{cb_eMinute.Text}:{cb_eSecond.Text}";
            oPEvent.ShowDialog();
        }


    }
}
